package com.qf.air.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.air.entity.Air;
import com.qf.air.enums.AirEnum;
import com.qf.air.exception.AirEx;
import com.qf.air.mapper.AirMapper;
import com.qf.air.service.AirService;
import com.qf.air.util.ElasticsearchUtil;
import com.qf.air.util.SearchUtil;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 维多利加
 * @Date: 2021/3/20 11:02
 */
@Service
public class AirServiceImpl implements AirService {
    @Autowired
    private AirMapper airMapper;
    @Override
    public PageInfo<Air> findByPageAndDistrictId(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) throws IOException, ParseException {
        PageHelper.startPage(page,rows);
        List<Air> all = airMapper.findByDistrictId(districtId,monitoringStation,startTime,endTime);
        PageInfo<Air> pageInfo = new PageInfo<>(all);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void save(Air air) throws IOException {
        Integer count = airMapper.save(air);

        List<Air> airs = airMapper.selectByMaxId();

        Air air1 = airs.get(0);

        IndexRequest request = new IndexRequest();
        request.index("air");
        Map map = new HashMap();
        map.put("id", air1.getId());
        map.put("districtId", air1.getDistrictId());
        map.put("monitorTime", air1.getMonitorTime());
        map.put("pm10", air1.getPm10());
        map.put("pm25", air1.getPm25());
        map.put("monitoringStation", air1.getMonitoringStation());
        map.put("lastModifyTime", air1.getLastModifyTime());
        map.put("districtName", air1.getDistrictName());
        request.id(String.valueOf(air1.getId()));
        request.source(map);
        IndexResponse resp = ElasticsearchUtil.getClient().index(request, RequestOptions.DEFAULT);
        if ("CREATED".equalsIgnoreCase(resp.getResult().getLowercase())) {
            System.out.println("添加文档成功！");
        }else{
            System.out.println("文档添加失败！");
        }

        if(count !=1){
            //添加失败，记录日志，抛出异常
            System.out.println("添加信息失败！ air="+air);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = -1,readOnly = false,rollbackFor = Exception.class,noRollbackFor = ArithmeticException.class)
    public void deleteById(Integer id) throws IOException {
        int i = airMapper.deleteById(id);

        RestHighLevelClient client = ElasticsearchUtil.getClient();
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.index("air");
        deleteRequest.id(String.valueOf(id));
        DeleteResponse response = client.delete(deleteRequest,RequestOptions.DEFAULT);

        if(i!=1){
            System.out.println("删除失败！ id="+id);
            throw new AirEx(AirEnum.AIR_DELETE_ERROR);
        }

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateById(Air air) throws IOException {
        int count = airMapper.updateById(air);

        RestHighLevelClient client = ElasticsearchUtil.getClient();
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("air");
        updateRequest.id(String.valueOf(air.getId()));

        Map map = new HashMap();
        map.put("id", air.getId());
        map.put("districtId", air.getDistrictId());
        map.put("monitorTime", air.getMonitorTime());
        map.put("pm10", air.getPm10());
        map.put("pm25", air.getPm25());
        map.put("monitoringStation", air.getMonitoringStation());
        map.put("lastModifyTime", air.getLastModifyTime());
        map.put("districtName", air.getDistrictName());
        updateRequest.doc(map);

        UpdateResponse response = client.update(updateRequest,RequestOptions.DEFAULT);

        if(count!=1){
            System.out.println("修改失败！ air="+air);
            throw new AirEx(AirEnum.AIR_UPDATE_ERROR);
        }
    }
}
